#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/3/14 3:08 PM
# @Author  : zhongxin
# @Email   : 490336534@qq.com
# @File    : reportoperator.py
import platform
import requests

from src.utils.constant import ProjectName, BUILD_NUMBER, BUILD_URL
from src.utils.logoperator import LogOperator
from src.utils.timeoperator import timeoperator

logger = LogOperator(__name__)


class ReportOperator:

    def __init__(self, hook: list):
        self.headers = {"Content-Type": "text/plain"}
        self.hook_url_list = [f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={i}" for i in hook]
        self.allure_url = f"http://jenkins.com/job/{ProjectName}/{BUILD_NUMBER}/allure/"
        self.test_system = {
            "Darwin": "MAC",
            "Linux": "Linux",
            "Windows": "Windows",
        }

    def send(self, data):
        send_data = {
            "msgtype": "markdown",  # 消息类型:markdown
            "markdown": {
                "content": data
            }
        }
        for hook_url in self.hook_url_list:
            try:
                response = requests.post(url=hook_url, headers=self.headers, json=send_data)
                logger.info(f"发送通知成功:{response.text}")
            except Exception as e:
                logger.error(f"发送企业微信消息失败:{e}")

    def send_msg(self, result='', other=''):
        data1 = f"""**【{ProjectName}】**
> 项目名称:{ProjectName}
> 构件编号:#{BUILD_NUMBER}
> 完成时间:{timeoperator.now1}
> 测试环境:{self.test_system.get(platform.system(), platform.system())}
> [报告链接]({self.allure_url})
> [控制台链接]({BUILD_URL})

{result}"""
        data = data1 + "\n" + other
        if len(data.encode()) > 4096:  # 最长不超过4096个字节，必须是utf8编码
            data = data1 + "\n" + "错误信息过多,分批发送"
            self.send(data)
            self.send_other(other)
        else:
            self.send(data)

    def send_other(self, data):
        data_list = data.split("\n")
        data_list = [i.strip() for i in data_list if i]
        data_list = [i for i in data_list if i and i != "失败用例:" and i != "异常用例:"]
        data_info = []
        for i in data_list:
            d1 = "\n".join(data_info)
            data_info.append(i)
            d2 = "\n".join(data_info)
            size2 = len(d2.encode())
            if size2 > 4096:
                self.send(d1)
                data_info = [i]
        self.send("\n".join(data_info))

    def change_run_detail(self, run_detail):
        passed_list = []
        failed_list = []
        error_list = []
        skipped_list = []
        for i in run_detail:
            parameter = ""
            steps = i.get('steps')
            if steps:
                steps = f"【步骤】:{steps}"
            if i.get('parameters', ''):
                parameter = f"({i.get('parameters', '')})"
            if i.get('status') == 'passed':
                passed_list.append(f"{i.get('labels')}:{i.get('fullName')} {parameter}")
            elif i.get('status') == 'failed':
                failed_list.append(
                    f"{i.get('labels')}:{i.get('fullName')}{parameter}<font color=#009900 >{steps}</font><font color=#ff0000 >{i['statusDetails']['message']}</font>")
            elif i.get('status') in ['error', 'broken']:
                error_list.append(
                    f"{i.get('labels')}:{i.get('fullName')}{parameter}<font color=#009900 >{steps}</font><font color=#ff0000 >{i['statusDetails']['message']}</font>")
            elif i.get('status') == 'skipped':
                skipped_list.append(f"{i.get('labels')}:{i.get('fullName')} {parameter}")
        return passed_list, failed_list, error_list, skipped_list
